package tichu_project252.Controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import tichu_project252.CardClasses.Card;
import tichu_project252.Model.Model;
import tichu_project252.View.GameFrame;
import tichu_project252.View.Player.passButton;

/**
 * Handles the Pass button.
 *
 * <p> <b> Invariants: </b> </p>
 *
 * @author Alexandra Barka, ΑΜ: 2867, login : barka.
 * @author Euaggelia Petauraki AM: 2875 login: petavraki.
 * @version %I%, %G%
 *
 */
public class passHandler extends Controller implements ActionListener {

    /**
     * The passHandler defines the behavior of the "Pass" buttons when an action
     * is performed on them.
     *
     * <p><b>Constructor: </b> passHandler(Model m)</p>
     *
     * <p><b>Precondition: </b> There is a model </p> <p><b>Postcondition: </b>
     * constructs a valid controller </p>
     *
     * @see <a
     * href="http://docs.oracle.com/javase/tutorial/java/IandI/super.html">super</a>
     *
     */
    public passHandler(Model m) {
        super(m);
    }

    /**
     * Invoked when an action occurs.
     *
     * <p><b>Precondition: </b> The button is pushed </p> <p><b>Postcondition:
     * </b> The method handlePass() is performed. </p>
     *
     * @see ActionListener
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        JButton temp = (JButton) e.getSource();
        GameFrame g = (GameFrame) temp.getParent().getParent().getParent().getParent().getParent().getParent().getParent(); // find the gameframe

        passButton button = (passButton) temp;   //find the passbutton
        int player = button.getPlayer(); // and the player pushes it
        boolean flag = m.handlePass(player); // find if player push the pass


        if (flag) {  //if the button is pushed

            LinkedList<Card> templist = new LinkedList<Card>();

            m.getTable().getTrick(templist);  // put the trick in the templist

            try {
                m.getPlayer(player).setTrick(templist); // and put the cards into the players trick pile
                g.addtoPile(templist, player); //add to pile in graphics
                g.clearCenterPile(); //clear the cards from the center

            } catch (IOException ex) {
                Logger.getLogger(passHandler.class.getName()).log(Level.SEVERE, null, ex);  // if something goes wrong
            }

        }
        
        g.enablePlayer(m.getCurrent()); // Enable the buttons to next player

    }
}
